package com.yiyuan.system.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import com.yiyuan.common.base.BaseDao;
import com.yiyuan.system.dao.IGroupDao;
import com.yiyuan.system.model.Group;

@Repository("groupDao")
public class GroupDaoHbImpl extends BaseDao implements IGroupDao {
	public void add(Group group) {
		this.getHibernateTemplate().save(group);
	}

	@SuppressWarnings("unchecked")
	public List<Group> findList(int startIndex, int endIndex,String groupName) {
		Session session = this.getSession();
		String hql="from Group";		
		if(groupName!=null && !groupName.equals("")){
			hql +=" where groupName like '%'||:groupName||'%'";
		}
		Query query = session.createQuery(hql);
		if(groupName!=null && !groupName.equals("")){
			query.setString("groupName", groupName);
		}
		query.setFirstResult(startIndex - 1);
		query.setMaxResults(endIndex);
		List<Group> list = query.list();
		return list;
	}

	public int getPageCount(String groupName) {
		Session session = this.getSession();
		String hql="select count(groupId) from Group";		
		if(groupName!=null && !groupName.equals("")){
			hql +=" where groupName like '%'||:groupName||'%'";
		}
		Query query = session.createQuery(hql);
		if(groupName!=null && !groupName.equals("")){
			query.setString("groupName", groupName);
		}
		int count = Integer.parseInt(query.uniqueResult().toString());
		return count;
	}

	public void update(Group group) {
		this.getHibernateTemplate().update(group);
	}

	public Group get(Integer groupId) {
		return (Group) this.getHibernateTemplate().get(Group.class, groupId);
	}

	public void delete(Group group) {
		this.getHibernateTemplate().delete(group);
	}

	@SuppressWarnings("unchecked")
	public List<Group> findList(Integer userId) {
		Session session = this.getSession();
		Query query = session.createQuery("from Group where userId=:userId");
		query.setInteger("userId", userId);
		List<Group> list = query.list();
		return list;
	}

}
